package com.ldfile.server.utils;

import com.alibaba.fastjson.JSONObject;
import com.ldfile.server.entity.FileResponseEntity;
import com.ldfile.server.exception.FileServerException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import com.ldfile.server.config.FileServiceInfoConfiguration;

@Configuration
@RequestMapping("config")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class wechatQRCodeUtils {
    private final FileServiceInfoConfiguration fileServiceInfoConfiguration;
    @Value("${wechat.appid:222}")
    private  String appid;
    @Value("${wechat.secret:333}")
    private  String secret;

    public  String getToken() {
        try {
            Map<String, String> map = new LinkedHashMap<String, String>();
            map.put("grant_type", "client_credential");
            map.put("appid", appid);//改成自己的appid
            map.put("secret", secret);
            String rt = httpUtils.sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
            System.out.println("what is:" + rt);
            JSONObject json = JSONObject.parseObject(rt);
            if (json.getString("access_token") != null || json.getString("access_token") != "") {
                return json.getString("access_token");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /*
     * 获取 二维码图片
     *
     */
    public FileResponseEntity getminiqrQr(String accessToken,String fileName,String page,String scene) throws FileServerException {
        String codeUrl =fileServiceInfoConfiguration.getDirYml() + File.separator +"QRcode" + File.separator+ fileName;
        File file = new File(codeUrl);
        if(file.exists()){
            String filedir=fileServiceInfoConfiguration.getUrlYml() + fileServiceInfoConfiguration.getPathYml() +"/"+"QRcode" + "/" + fileName;
            return FileResponseEntity.builder().success(false).result("小程序码已存在，可直接请求访问！地址："+filedir).build();
        }
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene);
            paramJson.put("page", page);
            paramJson.put("width", 430);
            paramJson.put("is_hyaline", true);
            paramJson.put("auto_color", true);
            /**
             * line_color生效
             * paramJson.put("auto_color", false);
             * JSONObject lineColor = new JSONObject();
             * lineColor.put("r", 0);
             * lineColor.put("g", 0);
             * lineColor.put("b", 0);
             * paramJson.put("line_color", lineColor);
             * */

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File(codeUrl));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
            return FileResponseEntity.builder().success(true).result(fileServiceInfoConfiguration.getUrlYml() + fileServiceInfoConfiguration.getPathYml() +"/"+"QRcode" + "/" + fileName).build();
        } catch (Exception e) {
            e.printStackTrace();
            return FileResponseEntity.builder().success(false).result(e.getMessage()).build();
        }

    }

}
